package com.finance.capacity.coefficientSummary.controller;

import com.finance.base.constant.BaseConstants;
import com.finance.capacity.coefficientSummary.request.CoeSummaryReq;
import com.finance.capacity.siteCoefficientMonth.bean.pojo.SiteCoeMonth;
import com.finance.capacity.siteCoefficientMonth.bean.pojo.SiteCoeMonthList;
import com.finance.capacity.siteCoefficientMonth.capService.ISiteCoefficientMonthService;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: ly
 * @Date: Created in 2017-08-28
 */
@Controller
@RequestMapping("/capacity/coeSummary")
public class CoeSummaryController extends BaseController {

    @Resource
    private ISiteCoefficientMonthService siteCoefficientMonthService;

    @RequestMapping("/list")
    public Result getCoeSummaryList(CoeSummaryReq form){
        Page page = Page.getInstance(form);
        SiteCoeMonthList siteCoeMonthList = this.requestDeal(form);
        page.setParams(siteCoeMonthList);

        PageResultBO<SiteCoeMonth> resultBO = siteCoefficientMonthService.coeSummaryList(page);
        return getSuccessResult(resultBO);
    }

    @RequestMapping("/export")
    public Result exportSiteCoeSummary(CoeSummaryReq form, HttpServletResponse response) throws UnsupportedEncodingException {
        SiteCoeMonthList siteCoeMonthList = this.requestDeal(form);

        List<SiteCoeMonth> exportList = siteCoefficientMonthService.exportSiteCoeSummary(siteCoeMonthList);
        if (exportList.size() > 0) {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "公平系数汇总列表_" + df.format(new Date()); // 文件名
            String lastStr = ".xls";// 文件名后缀
            fileName = fileName + lastStr;

            // 声明一个工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet("公平系数汇总列表信息");
            sheet.createDrawingPatriarch();//
            HSSFRow row = sheet.createRow(0);
            String[] title = new String[]{"序号", "省公司", "市公司", "站点", "总单量", "总出勤", "平均单量", "公平系数", "日期"};
            for (int i = 0; i < title.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }

            for (int i = 0; i < exportList.size(); i++) {
                SiteCoeMonth t = (SiteCoeMonth) exportList.get(i);
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(i + 1);
                row.createCell(1).setCellValue(t.getProvinceName());
                row.createCell(2).setCellValue(t.getCityName());
                row.createCell(3).setCellValue(t.getSiteName());
                row.createCell(4).setCellValue(t.getOrderTotalNum());
                row.createCell(5).setCellValue(t.getWorkerNum());
                row.createCell(6).setCellValue(t.getOrderAvgNum());
                row.createCell(7).setCellValue(String.valueOf(t.getSiteCoefficient()));
                row.createCell(8).setCellValue(t.getSiteMonth());
            }

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream out;
            try {
                out = response.getOutputStream();
                workbook.write(out);
                out.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return getFailResult(BaseConstants.ERR_INVALID_PARAMETER, BaseConstants.getErrorMessage(BaseConstants.ERR_INVALID_PARAMETER) );
            }
            return null;
        } else {
            return getFailResult(BaseConstants.ERR_RESULT_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_RESULT_NULL) );
        }
    }

    private SiteCoeMonthList requestDeal( CoeSummaryReq form ){
        SiteCoeMonthList siteCoeMonthList = new SiteCoeMonthList();
        if( !"-1".equals(form.getSiteId()) ){
            siteCoeMonthList.setProvinceId("-1");
            siteCoeMonthList.setCityId("-1");
            siteCoeMonthList.setSiteId(form.getSiteId());
        }else if( !"-1".equals(form.getCityId()) ){
            siteCoeMonthList.setProvinceId("-1");
            siteCoeMonthList.setCityId(form.getCityId());
            siteCoeMonthList.setSiteId("-1");
        }else if( !"-1".equals(form.getProvinceId()) ){
            siteCoeMonthList.setProvinceId(form.getProvinceId());
            siteCoeMonthList.setCityId("-1");
            siteCoeMonthList.setSiteId("-1");
        }
        if( StringUtils.isNotBlank(form.getSiteMonths()) && form.getSiteMonths().contains("X") ){
            String siteMonth = form.getSiteMonths().replace("X","%");
            siteCoeMonthList.setSiteMonth(siteMonth);
            siteCoeMonthList.setMonthStatus(1);
        }else{
            List<String> siteMonth = Arrays.asList(form.getSiteMonths().split(","));
            siteCoeMonthList.setSiteMonths(siteMonth);
            siteCoeMonthList.setMonthStatus(0);
        }
        if( StringUtils.isNotBlank(form.getKeyWords()) ){
            List<String> keyWordsList = Arrays.asList(form.getKeyWords().split("、"));
            siteCoeMonthList.setKeyWords(keyWordsList);
        }
        return siteCoeMonthList;
    }

}
